package book.zone.model;

import book.zone.log.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: NDemeshchenko
 * Date: May 28, 2010
 * Time: 4:03:48 PM
 */
public class CartModel {
    int[] cartItems;
    String[] cartToReturn;
    public CartModel(){}

    public CartModel(Object[] cartItems) {
        this.cartItems = new int[cartItems.length];
        for(int i=0;i<cartItems.length; i++){
            this.cartItems[i] = Integer.parseInt((String) cartItems[i]);
        }
        System.out.println(Arrays.toString(this.cartItems));
    }


    public String[] getItemsFromDatabase(int book_id){
        String selectStatement = "select BOOKS.book_id, BOOKS.title, BOOKS.author1, BOOKS.author2, BOOKS.author3, BOOKS.publish_date, BOOKS.img_url, PRICES.book_price FROM BOOKS JOIN PRICES " +
                                    "WHERE BOOKS.book_id=PRICES.book_id " +
                                    "AND (BOOKS.book_id =" + book_id + ");";
        try{
            Context ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/bookzone");
            if (ds != null) {
                Connection conn = ds.getConnection();
                if(conn != null){
                    Statement stmt = conn.createStatement();
                    ResultSet rst = stmt.executeQuery(selectStatement);
                    if (rst.next()){
                        cartToReturn = new String[] {
                                rst.getString("book_id"),
                                rst.getString("title"),
                                rst.getString("author1"),
                                rst.getString("author2"),
                                rst.getString("author3"),
                                rst.getString("publish_date"),
                                rst.getString("img_url"),
                                rst.getString("book_price")};
                    }
                    stmt.close();
                    conn.close();
                }
            }
            else{
                Logger.out("Not Connected. Check in SignInModel");
            }
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.cartToReturn;
    }
}
